var httpTools = (function () {
    return {
        // post请求
        postRequest: function (vue, url, param, success, err) {
            vue.$http.post(url, param).then(function (data) {
                var code = data.body.errCode;
                if (code == '0000') {
                    success(data);
                } else if (code == '9898') {
                    webViewTools.call('login', {});
                }
            }, function (error) {
                err();
            })
        },
        // get请求
        getRequest: function (vue, url, param, success, err) {
            vue.$http.get(url, {params: param}).then(function (data) {
                var code = data.body.errCode;
                if (code == '0000') {
                    success(data);
                } else if (code == '9898') {
                    webViewTools.call('login', {});
                }
            }, function (error) {
                err();
            })
        },
        // 并发请求
        concurrentRequest: function (vue, url, param, success, err) {

        }, /*
         // 调用拦截器
         initInterceptors: function (vue) {
         vue.http.interceptors.push((request, next) => {
         //登录成功后将后台返回的TOKEN在本地存下来,每次请求从sessionStorage中拿到存储的TOKEN值
         let TOKEN = sessionStorage.getItem('STORAGE_TOKEN');
         if (TOKEN) {
         //如果请求时TOKEN存在,就为每次请求的headers中设置好TOKEN,后台根据headers中的TOKEN判断是否放行
         request.headers.set('token', TOKEN);
         } else {
         setupWebViewJavascriptBridge(function (bridge) {
         // 跳到登录
         bridge.callHandler('login', {}, {});
         });
         }
         next((response) => {
         return response;
         });
         });
         },*/
        // 设置token,userId 到session中
        setSessionStorage: function (token, userId) {
            var sStorage = window.sessionStorage;
            if (tools.isNotNull(token)) {
                sStorage.setItem("STORAGE_TOKEN", token);
            }
            if (tools.isNotNull(userId)) {
                sStorage.setItem("STORAGE_USER_ID", userId);
            }
        }
    }
})();
/**
 * 常用工具方法
 * @type {{isNull, isNotNull, isFunction, log, getQueryString, trim, isWeiXin, getDate}}
 */
var tools = (function () {

    function pri_isNull(obj) {

        if (obj == null || typeof obj == "undefined" || obj == "" || obj.length == 0) {
            return true;
        }

        return false;
    }

    return {
        isNull: function (obj) {
            return pri_isNull(obj);
        },
        isNotNull: function (obj) {
            return !pri_isNull(obj);
        },
        /**
         * 是否还有下页数据
         * @param list
         * @param pageSize
         * @returns {boolean}
         */
        isNextPage: function (list, pageSize) {
            var page = 10;
            if (tools.isNotNull(pageSize)) {
                page = pageSize;
            }
            if (tools.isNotNull(list) && list.length == page) {
                return true;
            }
            return false;
        },
        isFunction: function (obj) {
            return typeof obj == "function";
        },
        log: function (msg) {
            console.dir(msg);
        },
        getQueryString: function (name) {
            var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
            if (result == null || result.length < 1) {

                return "";

            }
            return result[1];
        },
        /**
         * 去除空字符串
         * @param str 来源字符串
         * @param is_global 是否去除中间的空格
         * @returns {string|XML|void|*}
         */
        trim: function (str, is_global) {
            var result;
            result = str.replace(/(^\s+)|(\s+$)/g, "");
            if (is_global) {
                result = result.replace(/\s/g, "");
            }
            return result;
        },
        isWeiXin: function () {
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                return true;
            } else {
                return false;
            }
        },
        getDate: function (strDate) {
            strDate = strDate.replace(/-/g, "/");
            return new Date(strDate);
        },
        uniqueId: function () {
            var ramdomLength = 11;
            return Number(Math.random().toString().substr(3, ramdomLength) + Date.now()).toString(36);
        },
        version: function () {
            if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {  //判断iPhone|iPad|iPod|iOS
                //alert(navigator.userAgent);
                return "iOS";
            } else if (/(Android)/i.test(navigator.userAgent)) {   //判断Android
                return "android";                                         //alert(navigator.userAgent);
            } else {  //pc
                return "android";
            }
        }
    }
})();

/**
 * 日志工具类
 * @type {{msg}}
 */
var log = (function () {

    return {
        msg: function (info, obj) {
            console.warn(info);
            if (tools.isNotNull(obj)) {
                console.log(obj);
            }
        }
    }

})();

/**
 * 请求操作
 * @type {{goTo}}
 */
var request = (function () {
    return {
        /**
         * 跳转到某个地址
         * @param href 地址
         * @param data 存储的数据
         */
        goTo: function (href, data) {
            if (tools.isNotNull(data)) {
                dataTool.store("_request.data." + href, data);
            }
            location.href = href;
        },
        /**
         * 读取数据
         * @returns {*}
         */
        getData: function () {
            var href = window.location.href;
            var hrefArr = href.split("/");
            var data = dataTool.read("_request.data." + hrefArr[hrefArr.length - 1]);
            log.msg("request.getData", data);
            return data;
        }
    }
})();

/**
 * 页面初始化工具类
 * @type {{finish}}
 */
var pageInit = (function () {
    var _initCallback = null;
    var _beforeCallback = null;

    $(function () {
        if (tools.isFunction(_beforeCallback)) {
            _beforeCallback();
        }
        if (tools.isFunction(_initCallback)) {
            _initCallback();
        }
    });
    return {
        before: function (callback) {
            _beforeCallback = callback;
        },
        finish: function (callback) {
            _initCallback = callback;
        }
    }
})();

/**
 * 弹出层帮助方法
 * @type {{loading, msg, close, closeAll}}
 */
var layerTool = (function () {

    return {
        loading: function () {
            return layer.open({
                type: 2,
                content: "努力加载中",
                shade: 'background-color:transparent',
                shadeClose: false,
            });
        },
        msg: function (msg, callback) {
            return layer.open({
                content: msg
                , skin: 'msg'
                , time: 2 //2秒后自动关闭
                , end: function () {
                    if (tools.isFunction(callback)) {
                        callback();
                    }
                }
            });
        },
        close: function (index) {
            if (tools.isNotNull(index)) {
                layer.close(index);
            } else {
                layer.close(0);
            }
        },
        closeAll: function () {
            layer.closeAll();
        }
    }

})();
/**
 * 数据存储帮助方法
 * @type {{store, read, readOnce}}
 */
var dataTool = (function () {

    return {
        store: function (key, val) {
            val = JSON.stringify(val);
            localStorage.setItem(key, val);
        },
        read: function (key) {
            var data = localStorage.getItem(key);
            if (tools.isNotNull(data)) {
                data = JSON.parse(data);
            }
            return data;
        },
        readOnce: function (key) {
            var data = localStorage.getItem(key);
            if (tools.isNotNull(data)) {
                data = JSON.parse(data);
            }
            localStorage.removeItem(key);
            return data;
        },
        remove: function (key) {
            localStorage.removeItem(key);
        }
    };
})();
/**
 * 数据共享服务
 * @type {{data, removeData}}
 */
var shareDataTool = (function () {
    return {
        /**
         * 跨框架数据共享接口
         * @param {String} 存储的数据名
         * @param {Any} 将要存储的任意数据(无此项则返回被查询的数据)
         */
        data: function (name, value) {
            var top = window.top,
                cache = top['_CACHE'] || {};
            top['_CACHE'] = cache;

            return value !== undefined ? cache[name] = value : cache[name];
        }
        ,

        /**
         * 数据共享删除接口
         * @param {String} 删除的数据名
         */
        removeData: function (name) {
            var cache = window.top['_CACHE'];
            if (cache && cache[name]) delete cache[name];
        }
    }

})();
/**
 * 日期工具类
 * @type {{getWeek}}
 */
var dateTools = (function () {
    return {
        /**
         * 根据时间字符串获取当前星期几
         * @param dateStr 时间（字符串）
         * @returns {string}星期几
         */
        getWeek: function (dateStr) {
            var d = new Date(dateStr);
            var w = d.getDay();
            var arr = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
            return arr[w];
        },
        /**
         * 比较当前时间与指定时间的大小
         * @param dateStr 时间（字符串）
         * @returns 1 当前时间大于指定时间，0 当前时间等于指定时间，-1 当前时间小于指定时间
         *
         */
        compareTime: function (dateStr) {
            var d = new Date(dateStr);
            var sys = new Date();
            if (sys > d) {
                return 1;
            } else if (sys < d) {
                return -1;
            } else {
                return 0;
            }
        },
        /**
         * 比较时间与时间的大小
         * @param dateStr 时间（字符串）
         * @returns 1 时间1大于时间2，0 相等，-1 时间1小于时间2
         *
         */
        compareToTime: function (dateStr1, dateStr2) {
            var date1 = new Date(dateStr1);
            var date2 = new Date(dateStr2);
            if (date1 > date2) {
                return 1;
            } else if (date1 < date2) {
                return -1;
            } else {
                return 0;
            }
        }
    };
})();
/**
 * vue下拉刷新+无限加载
 *<link rel="stylesheet" href="style/css/page.css">
 *  <script type="text/javascript" src="style/js/include.js"></script>
 *  <script src="thirdParty/jroll/jroll.js"></script>
 *  <script src="thirdParty/jroll/jroll-vue-infinite.js"></script>
 *  <script src="thirdParty/jroll/jroll-pulldown.1.0.0.js"></script>
 *  <jroll-infinite class="jroll-vue-infinite container">
 *      <ul></ul>
 *  </jroll-infinite>
 * @type {{init, option}}
 */
var page = (function () {

    var _pullDownAction = null;
    var _pullUpAction = null;
    var _option = null;
    var _component = null;


    function _initStyle() {
        var jroll = $(".jroll-vue-infinite");
        if (tools.isNotNull(jroll)) {
            var topOffset = $(jroll).offset().top;
            // var jroll_next = $("div[jroll-id*='scroller']");
            $(jroll).css({
                "height": "calc(100% -  100px)"
            });
            if (typeof _option.pullUpAction == "undefined") {
                $(".jroll-infinite-tip").hide();
            }
        }
    }

    function initStyle() {
        pageInit.finish(function () {
            _initStyle();
        });
    }

    function bottomed(complete) {
        ;
        _component = this;
        var me = this;
        if (me.page == -1) {
            me.tip = "我是有底线的";
            return;
        }
        if (typeof complete == "function") {
            console.log("下拉刷新");
            _pullDownAction(1, function (status) {
                if (status == 0) {
                    me.tip = "我是有底线的";
                    me.page = -1;
                } else {
                    me.page = 1;
                    me.tip = "上拉加载更多数据";
                }
                if (tools.isFunction(complete)) {
                    complete();
                }
            });
        } else {
            me.tip = "正在加载中...";
            if (me.page == 0) {
                console.log("首次加载刷新");
                _pullDownAction(1, function (status) {
                    me.page++;
                    if (status == 0) {
                        me.tip = "我是有底线的";
                        me.page = -1;
                    } else {
                        me.page = 1;
                        me.tip = "上拉加载更多数据";
                    }
                    if (tools.isFunction(complete)) {
                        complete();
                    }
                });
                return;
            }
            console.log("上拉加载");
            _pullUpAction(me.page, function (status) {
                if (status == 0) {
                    me.tip = "我是有底线的";
                    me.page = -1;
                } else {
                    me.tip = "上拉加载更多数据";
                    me.page++;
                }
            });
        }
    }

    var infOptions = {
        updated: function () {
            console.log('current page is ' + this.page)
        }
    };

    return {
        init: function (option) {
            if (tools.isNotNull(infOptions.bottomed)) {
                bottomed(undefined);
            }
            _option = option;
            if (typeof option.pullUpAction != "undefined") {
                _pullUpAction = option.pullUpAction;
            }
            infOptions.bottomed = bottomed;

            if (typeof option.pullDownAction != "undefined") {
                infOptions.pulldown = {};
                _pullDownAction = option.pullDownAction;
            }
            initStyle();
        },
        /**
         * 重置组件
         * page = 0
         * 滚动到最顶部
         * 调用首次加载方法
         */
        reset: function () {
            _component.page = 0;
            _component.jroll.scrollTo(0, 0);
            infOptions.bottomed.call(_component);
        },
        end: function (status) {
            if (tools.isNull(_component)) {
                return;
            }
            if (status == 0) {
                _component.tip = "我是有底线的";
                _component.page = -1;
            } else if (status == 1) {
                _component.tip = "上拉加载更多";
                _component.page = 1;
            } else {
                _component.tip = "未知错误";
                _component.page = 1;
            }
        },
        option: infOptions,
        jrollOption: {
            id: "scroller",
            scrollBarY: true
        }
    }
})();

/**
 * 随机数工具类
 * @type {{getNum}}
 */
var randomNum = (function () {
    function formatBallNumber(randomValue) {
        if (randomValue < 10) {
            return "0" + randomValue;
        } else {
            return randomValue + '';
        }
    }

    return {
        /**
         * 获取不重复随机数
         * @param integer start 随机数最小值
         * @param integer end 随机数最大值
         * @param integer size 随机数获取数量 最小为1，默认1
         * @param Bool isNotFormatStr 是否需要格式化为str
         * @param Array excludeArr 需要排除的数
         * @return integer|array 如 1或者[2,4,7,9]
         */
        getNum: function (start, end, size, isNotFormatStr, excludeArr) {
            // 全部随机数值
            var allNums = new Array();
            //判断获取随机数个数
            size = size ? (size > end - start ? end - start : size) : 1;
            // 生成随机数值区间数组
            for (var i = start, k = 0; i <= end; i++, k++) {
                // 排除需要排除的数
                if (excludeArr) {
                    var isRepeat = false;
                    for (var j = 0; j < excludeArr.length; j++) {
                        if (excludeArr[j] === i) {
                            isRepeat = true;
                            break;
                        }
                    }
                    if (isRepeat) {
                        k--;
                    } else {
                        allNums[k] = isNotFormatStr ? i : formatBallNumber(i);
                    }
                } else {
                    allNums[k] = isNotFormatStr ? i : formatBallNumber(i);
                }
            }
            // 打乱数组排序
            allNums.sort(function () {
                return 0.5 - Math.random();
            })
            // 获取数组从第一个开始到指定个数的下标区间
            // if (size === 1) {
            //     return [allNums[0]];
            // }
            if (size > 1) {
                return allNums.slice(0, size);
            } else {
                return allNums.slice(0, size).join("");
            }
        },
    }
})();
/**
 * 掩藏指定字符 135****8888
 * @type {{split}}
 */
var strReplace = (function () {
    /**
     * 例子：
     * strReplace.split('13583169084','',3,4,'*');
     * 13583169084  ==>   135****9084
     *
     * 将字符串切分替换为预定格式的数组
     * @param data  要切分的字符串
     * @param str   分隔符
     * @param first 首部显示原值的字符数
     * @param last  尾部显示原值的字符数
     * @param instal 替换的字符
     * @return  切分后的数组
     */
    return {
        split: function (data, str, first, last, instal) {
            if (tools.isNotNull(data)) {
                var arr = []
                data.split(str).forEach(function (val, index, arrmy) {
                    if (index > first - 1 && index <= arrmy.length - 1 - last) {
                        arr.push(instal)
                        return
                    }
                    arr.push(val)
                })
                return arr
            }
            return [];
        }
    }
})();
/**
 * 对象的深copy
 */
var copy = (function () {

    return {
        /**
         * @param obj   要clone的对象
         * @return      clone对象
         */
        deepCoby: function (obj) {
            // Handle the 3 simple types, and null or undefined
            if (null == obj || "object" != typeof obj)
                return obj;
            // Handle Date
            if (obj instanceof Date) {
                var copy = new Date();
                copy.setTime(obj.getTime());
                return copy;
            }

            // Handle Array
            if (obj instanceof Array) {
                var copy = [];
                for (var i = 0, len = obj.length; i < len; ++i) {
                    copy[i] = this.deepCoby(obj[i]);
                }
                return copy;
            }
            // Handle Object
            if (obj instanceof Object) {
                var copy = {};
                for (var attr in obj) {
                    if (obj.hasOwnProperty(attr)) copy[attr] = this.deepCoby(obj[attr]);
                }
                return copy;
            }
            throw new Error("Unable to copy obj! Its type isn't supported.");
        }
    }
})();


var webViewTools = (function () {

    function setupWebViewJavascriptBridge(callback) {
        if (window.WebViewJavascriptBridge) {
            return callback(WebViewJavascriptBridge);
        }
        if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
        }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function () {
            document.documentElement.removeChild(WVJBIframe)
        }, 0)
    }

    return {
        call: function (method, param) {
            var version = tools.version();
            if (version == "android") {
                setupWebViewJavascriptBridge(function (bridge) {
                    // 猜你喜欢 跳转更多页面

                    bridge.callHandler(method, param, function () {

                    });
                });
            } else {
                window.webkit.messageHandlers[method].postMessage(param);
            }

        },
        registMethod: function (method, success) {
            setupWebViewJavascriptBridge(function (bridge) {
                bridge.registerHandler(method, function (data, responseCallback) {
                    success(data);
                })
            })
        },

    }
})();


